package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IAlertDataService;
import com.zzyl.system.mapper.SysUserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.AlertRuleMapper;
import com.zzyl.nursing.domain.AlertRule;
import com.zzyl.nursing.service.IAlertRuleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 报警规则Service业务层处理
 * 
 * @author zhai
 * @date 2025-01-15
 */
@Service
public class AlertRuleServiceImpl extends ServiceImpl<AlertRuleMapper, AlertRule> implements IAlertRuleService
{
    @Autowired
    private AlertRuleMapper alertRuleMapper;

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private IAlertDataService alertDataService;

    /**
     * 查询报警规则
     * 
     * @param id 报警规则主键
     * @return 报警规则
     */
    @Override
    public AlertRule selectAlertRuleById(Long id)
    {
        return alertRuleMapper.selectById(id);
    }

    /**
     * 查询报警规则列表
     * 
     * @param alertRule 报警规则
     * @return 报警规则
     */
    @Override
    public List<AlertRule> selectAlertRuleList(AlertRule alertRule)
    {
        return alertRuleMapper.selectAlertRuleList(alertRule);
    }

    /**
     * 新增报警规则
     * 
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int insertAlertRule(AlertRule alertRule)
    {
        return alertRuleMapper.insert(alertRule);
    }

    /**
     * 修改报警规则
     * 
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int updateAlertRule(AlertRule alertRule)
    {
        return alertRuleMapper.updateById(alertRule);
    }

    /**
     * 批量删除报警规则
     * 
     * @param ids 需要删除的报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleByIds(Long[] ids)
    {
        return alertRuleMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除报警规则信息
     * 
     * @param id 报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleById(Long id)
    {
        return alertRuleMapper.deleteById(id);
    }

    /**
     * 报警规则过滤
     */
    @Override
    public void alertFilter() {
        //1.查询有没有有效的规则
        long count = count(Wrappers.<AlertRule>lambdaQuery().eq(AlertRule::getStatus, 1));
        //2.判断规则是否为空，为空直接结束方法
        if (count == 0){
            return;
        }
        //3.方法不为空，则从Redis缓存中获取设备上的最新数据(所有设备的数据)
        List<Object> deviceDataLists = redisTemplate.opsForHash().values(CacheConstants.IOT_DEVICE_LAST_DATA);
        //4.判断从Redis缓存中拿到的数据是否为空，为空则直接结束方法
        if (CollectionUtil.isEmpty(deviceDataLists)){
            return;
        }
        //5.当数据不为空，则遍历获得的数据并交给报警处理器进行处理
        deviceDataLists.forEach(deviceData -> {
        List<DeviceData> deviceDataList = (List<DeviceData>) deviceData;
            //再次遍历每一个设备的最新数据，拿到其中的一个物模型数据，交给数据报警处理方法处理
            deviceDataList.forEach(data -> {
                alertFilter(data);
            });
        });
    }

    /**
     * 将遍历得到的数据交给报警处理器进行处理
     * @param data 获得的设备数据
     */

    private void alertFilter(DeviceData data) {
        //0.判断当前上报的数据是否超过了1分钟 60s
        LocalTime alarmTime = data.getAlarmTime().toLocalTime();
        LocalTime now = LocalTime.now();
        long between = ChronoUnit.SECONDS.between(alarmTime, now);
        if (between > 60){
            return;
        }
        //1.准备对应报警规则数据
        List<AlertRule> alertRule = list(Wrappers.<AlertRule>lambdaQuery()
                .eq(AlertRule::getProductKey, data.getProductKey())
                .eq(AlertRule::getStatus, 1)
                .eq(AlertRule::getFunctionId, data.getFunctionId())
                .in(AlertRule::getIotId,-1, data.getIotId())
                );
        //2.判断规则是否为空，为空则结束方法
        if (CollectionUtil.isEmpty(alertRule)){
            return;
        }
        //3.当判断规则不为空则遍历每一条规则
        alertRule.forEach(rule -> {
            deviceDataAlarmHandler(data,rule);
        });
    }

    /**
     * 校验每一条规则是否生效
     * @param data 设备中的数据
     * @param rule 报警规则
     */

    private void deviceDataAlarmHandler(DeviceData data, AlertRule rule) {
        //沉默周期Key
        String silentKey = "iot:silentKey:" + rule.getProductKey() + rule.getIotId() + rule.getFunctionId() + rule.getId();
        //持续周期Key
        String durationKey = "iot:durationKey:" + rule.getProductKey() + rule.getIotId() + rule.getFunctionId() + rule.getId();
        //1.判断是否在生效时间内
        LocalTime localTime = data.getAlarmTime().toLocalTime();
        String[] split = rule.getAlertEffectivePeriod().split("~");
        LocalTime start = LocalTime.parse(split[0], DateTimeFormatter.ofPattern("HH:mm:ss"));
        LocalTime end = LocalTime.parse(split[1], DateTimeFormatter.ofPattern("HH:mm:ss"));
        //2.如果不在生效时间内，直接返回结果
        if (localTime.isBefore(start) || localTime.isAfter(end)){
            return;
        }
        //3.如果在生效时间内，校验数据是否达到阈值
        //3.1获取到数据值和阈值和符号在进行比较
        Double dataValue = Double.valueOf(data.getDataValue());
        Double alertValue = rule.getValue();
        //进行数据值比较 如果 dataValue>alertValue 返回1，小于返回-1 等于 返回 0
        int compare = Double.compare(dataValue, alertValue);
        String operator = rule.getOperator();
        if (">=".equals(operator) && compare < 0 || "<".equals(operator) && compare >= 0){
            redisTemplate.delete(silentKey);
            return;
        }
        //4.判断是否是在沉默周期内
        //从Redis缓存中获取沉默周期
        Object period = redisTemplate.opsForValue().get(silentKey);
        //如果沉默周期不为空则直接返回
        if (ObjectUtil.isNotEmpty(period)){
            return;
        }
        //5.判断是否在持续周期内
        //从Redis中获取持续周期
        Integer duration = (Integer) redisTemplate.opsForValue().get(durationKey);
        //判断报警次数是否为空，为空直接将0改为1，不为空直接+1
        if (ObjectUtil.isEmpty(duration)){
            duration = 1;
        }else {
            duration = duration + 1;
        }
        //判断+1之后是否还是达到了持续周期
        if (!duration.equals(rule.getDuration())){
            redisTemplate.opsForValue().set(durationKey,duration);
            return;
        }
        //6.校验全部通过，当前数据出发报警
        //删除Redis缓存中的报警数据
        redisTemplate.delete(durationKey);
        //添加Redis缓存中的沉默周期
        redisTemplate.opsForValue().set(durationKey, 1, rule.getAlertSilentPeriod(), TimeUnit.MINUTES);

        //7.批量保存报警数据
        bashSaveAlertData(data,rule);
    }

    /**
     * 批量保存报警数据
     * @param data 设备数据
     * @param rule 报警规则
     */
    private void bashSaveAlertData(DeviceData data, AlertRule rule) {
        List<AlertData> alertDateList = new ArrayList<>();
        List<Long> userId;
        //查看需要报警的通知人
        if (rule.getAlertDataType() == 0){
            //老人数据异常
            //判断是随身设备还是固定设备
            if (data.getLocationType() == 0){
                //随身设备
                userId = deviceMapper.selectNursingIdsByIotIdWithElder(data.getIotId());
            }else {
                //固定设备
                userId = deviceMapper.selectNursingIdsByIotIdWithBed(data.getIotId());
            }
        }else {
            //设备数据异常
             userId = sysUserRoleMapper.selectUserIdByRoleName("维修工");
        }
        //查询管理员的id
        List<Long> memberUserId = sysUserRoleMapper.selectUserIdByRoleName("超级管理员");

        //将俩部分合起来
        userId.addAll(memberUserId);
        //遍历要通知的id列表，构造多条报警数据
        userId.forEach(userid -> {
            AlertData alertData = BeanUtil.toBean(data, AlertData.class);
            alertData.setId(null);
            alertData.setStatus(0);
            alertData.setUserId(userid);
            alertData.setAlertRuleId(rule.getId());
            String format = CharSequenceUtil.format("{}{}{},持续了{}个周期", rule.getFunctionName(), rule.getOperator(), rule.getValue(), rule.getDuration());
            alertData.setAlertReason(format);
            alertData.setType(rule.getAlertDataType());
            alertDateList.add(alertData);
        });

        //保存数据到报警数据表中
        alertDataService.saveBatch(alertDateList);
    }
}
